// 用户认证组件

class AuthComponent {
    constructor() {
        this.init();
    }
    
    init() {
        // 绑定事件
        this.bindEvents();
    }
    
    bindEvents() {
        // 登录表单提交事件
        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => this.handleLogin(e));
        }
        
        // 注册表单提交事件
        const registerForm = document.getElementById('registerForm');
        if (registerForm) {
            registerForm.addEventListener('submit', (e) => this.handleRegister(e));
        }
        
        // 登出事件
        const logoutLink = document.getElementById('logoutLink');
        if (logoutLink) {
            logoutLink.addEventListener('click', (e) => this.handleLogout(e));
        }
        
        // 首页按钮事件
        document.querySelectorAll('[data-target]').forEach(button => {
            button.addEventListener('click', (e) => {
                const target = button.getAttribute('data-target');
                this.navigateTo(target);
            });
        });
    }
    
    // 处理登录
    async handleLogin(e) {
        e.preventDefault();
        
        const phone = document.getElementById('loginPhone').value;
        const password = document.getElementById('loginPassword').value;
        
        // 简单验证
        if (!phone || !password) {
            this.showMessage('请填写手机号和密码', 'error');
            return;
        }
        
        try {
            // 显示加载状态
            this.setLoading(true, 'loginForm');
            
            // 调用后端API
            const response = await fetch('http://localhost:3003/api/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ phone, password })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // 保存token
                localStorage.setItem('authToken', data.token);
                localStorage.setItem('userId', data.user.id);
                localStorage.setItem('username', data.user.username);
                
                // 更新UI
                this.updateAuthState(true);
                
                // 更新首页内容
                this.updateHomePageContent(true);
                
                // 加载最近账单
                if (window.billsComponent) {
                    window.billsComponent.loadRecentBills();
                }
                
                // 跳转到仪表板
                this.navigateTo('dashboard');
                
                this.showMessage('登录成功', 'success');
            } else {
                this.showMessage(data.error || '登录失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Login error:', error);
        } finally {
            // 恢复按钮状态
            this.setLoading(false, 'loginForm');
        }
    }
    
    // 处理注册
    async handleRegister(e) {
        e.preventDefault();
        
        const username = document.getElementById('registerUsername').value;
        const phone = document.getElementById('registerPhone').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('registerConfirmPassword').value;
        
        // 简单验证
        if (!username || !phone || !password || !confirmPassword) {
            this.showMessage('请填写所有字段', 'error');
            return;
        }
        
        if (password !== confirmPassword) {
            this.showMessage('两次输入的密码不一致', 'error');
            return;
        }
        
        try {
            // 显示加载状态
            this.setLoading(true, 'registerForm');
            
            // 调用后端API
            const response = await fetch('http://localhost:3003/api/users/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, phone, password })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.showMessage('注册成功，请登录', 'success');
                // 切换到登录页面
                this.navigateTo('login');
            } else {
                this.showMessage(data.error || '注册失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Register error:', error);
        } finally {
            // 恢复按钮状态
            this.setLoading(false, 'registerForm');
        }
    }
    
    // 处理登出
    handleLogout(e) {
        e.preventDefault();
        
        // 清除认证信息
        localStorage.removeItem('authToken');
        localStorage.removeItem('userId');
        localStorage.removeItem('username');
        
        // 更新UI
        this.updateAuthState(false);
        
        // 更新首页内容
        this.updateHomePageContent(false);
        
        // 跳转到首页
        this.navigateTo('home');
        
        this.showMessage('已退出登录', 'success');
    }
    
    // 更新认证状态
    updateAuthState(isLoggedIn) {
        if (isLoggedIn) {
            // 显示用户相关功能
            document.querySelectorAll('.auth-required').forEach(el => {
                el.style.display = 'block';
            });
            
            // 隐藏登录相关功能
            document.querySelectorAll('.auth-not-required').forEach(el => {
                el.style.display = 'none';
            });
            
            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                const usernameElements = document.querySelectorAll('.username-display');
                usernameElements.forEach(el => {
                    el.textContent = username;
                });
            }
        } else {
            // 隐藏用户相关功能
            document.querySelectorAll('.auth-required').forEach(el => {
                el.style.display = 'none';
            });
            
            // 显示登录相关功能
            document.querySelectorAll('.auth-not-required').forEach(el => {
                el.style.display = 'block';
            });
        }
    }
    
    // 更新首页内容
    updateHomePageContent(isLoggedIn) {
        const guestContent = document.getElementById('guestHomeContent');
        const userContent = document.getElementById('userHomeContent');
        
        if (isLoggedIn) {
            // 显示用户内容，隐藏访客内容
            if (guestContent) guestContent.style.display = 'none';
            if (userContent) {
                userContent.style.display = 'block';
                // 更新用户名
                const username = localStorage.getItem('username');
                if (username) {
                    document.getElementById('welcomeUsername').textContent = username;
                }
                
                // 加载最近账单
                if (window.billsComponent) {
                    window.billsComponent.loadRecentBills();
                }
                
                // 加载仪表板数据
                if (window.dashboardComponent) {
                    window.dashboardComponent.loadDashboardData();
                }
            }
        } else {
            // 显示访客内容，隐藏用户内容
            if (guestContent) guestContent.style.display = 'block';
            if (userContent) userContent.style.display = 'none';
        }
    }
    
    // 页面导航
    navigateTo(page) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(pageEl => {
            pageEl.style.display = 'none';
        });
        
        // 显示目标页面
        const targetPage = document.getElementById(page + 'Page');
        if (targetPage) {
            targetPage.style.display = 'block';
            
            // 执行页面特定的初始化
            if (typeof window[page + 'PageInit'] === 'function') {
                window[page + 'PageInit']();
            }
            
            // 如果导航到首页，根据登录状态更新内容
            if (page === 'home') {
                const token = localStorage.getItem('authToken');
                this.updateHomePageContent(!!token);
            }
            
            // 如果导航到仪表板，加载相关数据
            if (page === 'dashboard' && window.dashboardComponent) {
                window.dashboardComponent.loadDashboardData();
            }
            
            // 如果导航到账单页面，加载账单数据
            if (page === 'bills' && window.billsComponent) {
                window.billsComponent.loadBills();
            }
        }
    }
    
    // 设置加载状态
    setLoading(loading, formId) {
        const form = document.getElementById(formId);
        if (form) {
            const submitButton = form.querySelector('button[type="submit"]');
            if (submitButton) {
                if (loading) {
                    submitButton.disabled = true;
                    submitButton.textContent = '处理中...';
                } else {
                    submitButton.disabled = false;
                    submitButton.textContent = formId === 'loginForm' ? '登录' : '注册';
                }
            }
        }
    }
    
    // 显示消息
    showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '15px 20px',
            borderRadius: '5px',
            color: 'white',
            fontWeight: 'bold',
            zIndex: '1000',
            boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
            transition: 'opacity 0.3s'
        });
        
        if (type === 'success') {
            messageEl.style.backgroundColor = '#4CAF50';
        } else {
            messageEl.style.backgroundColor = '#F44336';
        }
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            messageEl.style.opacity = '0';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
    
    // 检查用户登录状态
    checkAuthStatus() {
        const token = localStorage.getItem('authToken');
        this.updateAuthState(!!token);
        this.updateHomePageContent(!!token);
        return !!token;
    }
}

// 初始化认证组件
document.addEventListener('DOMContentLoaded', () => {
    window.authComponent = new AuthComponent();
    
    // 检查初始认证状态
    window.authComponent.checkAuthStatus();
    
    // 如果用户已登录，且当前在首页，则导航到仪表板
    const token = localStorage.getItem('authToken');
    if (token) {
        const currentPage = document.querySelector('.page[style*="display: block"]') || document.getElementById('homePage');
        if (currentPage && currentPage.id === 'homePage') {
            // 更新首页内容
            window.authComponent.updateHomePageContent(true);
            
            // 加载最近账单
            if (window.billsComponent) {
                window.billsComponent.loadRecentBills();
            }
            
            // 加载仪表板数据
            if (window.dashboardComponent) {
                window.dashboardComponent.loadDashboardData();
            }
        }
    }
});